package com.ljsw.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ljsw.activity.CKListInfoActivity;
import com.ljsw.activity.PKListInfoActivity;
import com.ljsw.activity.R;
import com.ljsw.adapter.AutoComperAdapter;
import com.ljsw.adapter.RenWuAdapter;
import com.ljsw.application.App;
import com.ljsw.dialog.DeleteDialog;
import com.ljsw.dialog.LoginDialog;
import com.ljsw.dialog.OneFingerDialog;
import com.ljsw.dialog.UserLoginDialog;
import com.ljsw.entity.RenWuClass;
import com.ljsw.entity.User;
import com.ljsw.server.UpServer;
import com.ljsw.util.Constant;
import com.ljsw.util.DialogManager;
import com.ljsw.util.FingerUtil.OnGetFingerListener;
import com.ljsw.util.Table;

import java.io.Serializable;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.ljsw.activity.CKListInfoActivity;

/**
 * 我的任务Fragment 碎片 作者: 石锚 版本: 1.0 日期: 2015-10-16
 */
public class MyRenwuFragment extends BaseFragment implements
        OnItemClickListener, OnItemLongClickListener, OnClickListener,
        OnGetFingerListener {
    public static final String state = "0";// 标识未完成的任务的状态
    private DialogManager dmanager;
    private LoginDialog dialog;// 获取任务Dialog
    private DeleteDialog deleteDialog;
    private OneFingerDialog onefingerDialog;// 指纹验证Dialog
    private UserLoginDialog useDialog;
    private RenWuClass rw;// 我的任务实体类
    private View view;// 视图
    private ListView renwu_list;// 我的任务
    private TextView back;//返回
    private TextView shuaxin;// ，刷新
    private TextView useryayun, renwu_shousuo;// 我的任务押运员人名 收索
    private ArrayList<RenWuClass> renwulist = new ArrayList<RenWuClass>();// 我的任务集合
    private RenWuAdapter adapter;// 我的任务适配器
    private Handler handler;// 消息
    private LinearLayout renwulayout, renwu_list_layout;
    private AutoCompleteTextView edit;
    private String str;// 输入车牌号接口返回的字符串
    private String cardmessage;//模糊查询返回值
    private String lingqustr;// 领取任务之后返回的字符串
    private TextView queding;// 确定
    private TextView youqingtishi;// 友情提示
    private TextView chepaihao;// 车牌号显示
    private List<String> plist;// 派工单 集合
    private MyRwListener listener;// 回调接口
    private Table[] tables;
    boolean flag = false;// 刷新键标识
    private String cid;// 车牌号
    private String cidet;//车牌号二
    private String cidtest;// 返回所有车车牌号
    private App app;
    private Bundle bundle;
    private User user;
    private String userId;// 用户登录的账号
    private String pwd;// 用户登录的密码
    private TextView zhuangxiangNum;
    public final static int RENWU_TAG = 1;
    private int times = 0;// 验证失败超过3次弹出窗口
    private boolean threeTimes = false;// 失败累计三次
    //    private FingerUtil mFingerUtil;
    private String[] carInfoArr;

    ArrayList<String> countries = new ArrayList<String>();//用于存放 集合数据
    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    ArrayList<String> strings = new ArrayList<String>();
    private AutoComperAdapter aAutoComperAdapter;//适配器
    private ArrayList<String> alt = new ArrayList<String>();
    private boolean flagtest = false;
    public SharedPreferences sp1;

    private String mrfname;

    public interface MyRwListener {// 回调接口

        public void tranmsg(String num);

        public void trancid(String cardId);
    }


    private LinearLayout lin_pc;//  盘库的 布局

    private LinearLayout lincheck;

    @SuppressLint("HandlerLeak")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_woderenwu, container, false);
        app = (App) getActivity().getApplication();

        getDiaog();
        plist = new ArrayList<String>();
        app.back = "back";
        initView();
        bundle = getArguments();
        if (bundle != null) {
            Log.e("myrf", bundle.getString("cid"));//四个值
            cid = bundle.getString("cid");// 车牌号
            chepaihao.setText(cid);
            edit.setText(cid);
        } else {
            bundle = new Bundle();
        }

//        if (!"9".equals(app.user.getUserId())) {

        if (!"9".equals("9")) {
            renwu_shousuo.setEnabled(false);
            renwu_shousuo
                    .setBackgroundResource(R.drawable.button_gray_selector);
        }

        flag = true;
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                dialog.dismiss();
                switch (msg.what) {
                    case 0:// 加载成功
                        // 更新车牌信息View
                        showView();
//                        if (mFingerUtil.getThread() != null) {
//                            mFingerUtil.stopFinger();
//                        }
                        break;
                    case 1:// 加载失败
                        // 车牌获取失败显示的视图
                        chepaihao.setText("车牌号:" + cid);
                        listener.tranmsg(0 + "");
                        app.size = renwulist.size();
                        renwulayout.setVisibility(View.GONE);
                        renwu_list_layout.setVisibility(View.VISIBLE);
                        queding.setEnabled(false);
                        queding.setBackgroundResource(R.drawable.button_gray_selector);
                        adapter.updateList(renwulist);
                        listener.tranmsg(renwulist.size() + "");
                        break;
                    case 2:// 加载失败
                        // 网络超时弹框
                        app.size = renwulist.size();
                        OnClick();
                        deleteDialog.setTitle("网络连接超时");
                        break;
                    case 3:// 加载失败
                        // 服务器挂掉弹框
                        app.size = renwulist.size();
                        OnClick();
                        deleteDialog.setTitle("加载异常");
                        break;
                    case 5:// 指纹验证成功
                        Toast.makeText(getActivity(), "该押运员已经绑定车牌号！",
                                Toast.LENGTH_LONG).show();
                        break;
                    case 6:
                        loadRenWu();
                        break;
                    case 7:
                        app.size = renwulist.size();
                        OnClickLingqu();
                        deleteDialog.setTitle("未领取到任务");
                        break;
                    case 8:
                        app.size = renwulist.size();
                        OnClickLingqu();
                        deleteDialog.setTitle("领取任务超时");
                        break;
                    case 9:
                        app.size = renwulist.size();
                        OnClickLingqu();
                        deleteDialog.setTitle("领取任务异常");
                        break;
                    case 10:// 获取登录框 回传过来的值
                        Bundle bundle = msg.getData();
                        userId = bundle.getString("name");
                        pwd = bundle.getString("pwd");
                        yanzhengUser(userId, pwd);
                        break;
                    case 11:// 用户验证成功

                        if (user.getUserId().equals(Constant.YyRoleId)) {
                            System.out.println("用户角色：=" + user.getUserId());
                            LingQuRenWu();
                        } else {

                            Toast.makeText(getActivity(), "请使用押运员领取任务",
                                    Toast.LENGTH_LONG).show();
                        }
                        break;
                    case 12:
                        Toast.makeText(getActivity(), app.fanhuiMsg,
                                Toast.LENGTH_SHORT).show();
                        OnLoginClick();
                        break;
                    case 13:
                        Toast.makeText(getActivity(), App.getApp().fanhuiMsg,
                                Toast.LENGTH_SHORT).show();
                        OnLoginClick();
                        break;
                    case 14:
                        Toast.makeText(getActivity(), App.getApp().fanhuiMsg,
                                Toast.LENGTH_SHORT).show();
                        OnLoginClick();
                        break;
                    case 16:
                        AutoComperAdapter<String> aater = new AutoComperAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, carInfoArr, AutoComperAdapter.ALL);
                        edit.setAdapter(aater);

//                        try {
//                            if (mrfname != null || !mrfname.equals("")) {
//                                cid = mrfname;
//                                app.cardId = cid;
//                            } else {
//                                Toast.makeText(getActivity(), "请输入车牌号", Toast.LENGTH_SHORT);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            Toast.makeText(getActivity(), "请输入车牌号" + e, Toast.LENGTH_SHORT);
//                        }
                        if ("".equals(cid) || cid == null) {
                            renwulayout.setVisibility(View.VISIBLE);
                            renwu_list_layout.setVisibility(View.GONE);
                            queding.setEnabled(false);
                            queding.setBackgroundResource(R.drawable.button_gray_selector);
                        } else {
                            loadRenWu();
                            renwulayout.setVisibility(View.GONE);
                            renwu_list_layout.setVisibility(View.VISIBLE);
                            renwu_list.setAdapter(adapter);
                            queding.setEnabled(true);
                            queding.setBackgroundResource(R.drawable.button_blue_selector);
                            chepaihao.setText("车牌号:" + cid);
                        }
                        break;
                    case 15:// 重试
                        //写一个封装的方法进行适配
                        OnClickGetCarId();
                        break;
                    case 17:
                        break;
                    case 18:
                        // 任务全部完成或没有任务允许接受其他任务
                        if (threeTimes) {
                            useDialog.show();
                            useDialog.setTitle("押运员验证");
                            return;
                        }
//                        if (mFingerUtil.getThread() == null) {
//                            mFingerUtil.startFinger();
//                        } else {
//                            mFingerUtil.startControl();
//                        }
                        onefingerDialog.show();
                    /*
                     * useDialog.show(); useDialog.setTitle("押运员验证");
					 */
                        break;
                    case 19:
                        // 任务未完成允许接受其他任务
                        deleteDialog.setTitle("该押运员与车不是绑定状态，您是否继续领取任务");
                        deleteDialog.show();
                        deleteDialog.setPositiveButton("确定", new OnClickListener() {

                            @Override
                            public void onClick(View arg0) {
                                if (threeTimes) {
                                    useDialog.show();
                                    useDialog.setTitle("押运员验证");
                                    return;
                                }
                                onefingerDialog.show();
//                                if (mFingerUtil.getThread() == null) {
//                                    mFingerUtil.startFinger();
//                                } else {
//                                    mFingerUtil.startControl();
//                                }
                            }
                        });
                        deleteDialog.setNegativeButton("取消", new OnClickListener() {

                            @Override
                            public void onClick(View arg0) {

                            }
                        });

					/*
                     * new AlertDialog.Builder(getActivity())
					 * .setMessage("该车牌号已绑定..") .setNegativeButton("确定", new
					 * DialogInterface.OnClickListener() {
					 *
					 * @Override public void onClick( DialogInterface arg0, int
					 * arg1) {
					 *
					 * openGetMissionDialog(); } }) .setPositiveButton("取消", new
					 * DialogInterface.OnClickListener() {
					 *
					 * @Override public void onClick( DialogInterface arg0, int
					 * arg1) { arg0.dismiss(); } }).show();
					 */
                        break;
                }
            }
        };

        useDialog.setmHandler(handler);//  添加数据源


        return view;
    }


    /**
     * 控件初始化
     */
    public void initView() {
        lin_pc = (LinearLayout) view.findViewById(R.id.lin_pc);
        lin_pc.setOnClickListener(this);
        lincheck = (LinearLayout) view.findViewById(R.id.lincheck);
        lincheck.setOnClickListener(this);
//        chepaihao = (TextView) view.findViewById(R.id.car_ren_num);// 车牌号
//        youqingtishi = (TextView) view.findViewById(R.id.youqingtishi);// 友情提示
//        edit = (AutoCompleteTextView) view.findViewById(R.id.xinxi_edit);// 输入框
//        edit.setThreshold(1);//第一个就提示
//        renwu_list = (ListView) view.findViewById(R.id.renwu_list);// 任务列表
//        useryayun = (TextView) view.findViewById(R.id.useryayun);// 押运员
//        renwu_shousuo = (TextView) view.findViewById(R.id.renwu_shousuo);// 任务收索
//        renwulayout = (LinearLayout) view.findViewById(R.id.renwulayout);
//        renwu_list_layout = (LinearLayout) view
//                .findViewById(R.id.renwu_list_layout);
//        queding = (TextView) view.findViewById(R.id.queding);// 领取任务确定
//        renwu_list.setOnItemClickListener(this);
//        renwu_list.setOnItemLongClickListener(this);
//        renwu_shousuo.setOnClickListener(this);
//        queding.setOnClickListener(this);
//        useryayun.setText("库管员：" + app.user.getName());
//        if (adapter == null) {
//            adapter = new RenWuAdapter(getActivity(), renwulist);
//
////            刷新
//        }
//        shuaxin = (TextView) getActivity().findViewById(R.id.shuaxin);
//        shuaxin.setOnClickListener(this);
        back = (TextView) getActivity().findViewById(R.id.back);
//        zhuangxiangNum = (TextView) getActivity().findViewById(
//                R.id.zhuangxiangNum);
        back.setOnClickListener(this);
        app = new App();
        Log.e("MYFragment---------", app.user.getUserId());
        if (app.user.getUserId().equals("4")) {/// 这段代码控制布局着显示隐藏   管库员4  管理员2
            lincheck.setVisibility(View.VISIBLE);
            lin_pc.setVisibility(View.GONE);
        } else if (app.user.getUserId().equals("2")) {
            lincheck.setVisibility(View.GONE);
            lin_pc.setVisibility(View.VISIBLE);
        } else {
            lincheck.setVisibility(View.GONE);
            lin_pc.setVisibility(View.GONE);
//            lincheck.setVisibility(View.VISIBLE);
//            lin_pc.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (mFingerUtil == null) {
//            mFingerUtil = new FingerUtil(getActivity(), this);
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    /**
     * 打开领取任务dialog
     */
    private void openGetMissionDialog() {
        deleteDialog.show();
        deleteDialog.setTitle("是否领取任务");
        deleteDialog.setPositiveButton("领取", new OnClickListener() {
            public void onClick(View arg0) {
                /* 判断押运员是否有其他任务 */
                noticeBindCar();
                /*
                 * useDialog.show(); useDialog.setTitle("押运员验证");
				 */
                // 判断押运员是否还有未完成任务
                /*
                 * dialog.show(); dialog.setMessage(""); new Thread(new
				 * Runnable() {
				 *
				 * @Override public void run() { // TODO Auto-generated method
				 * stub try { if (!UpServer.upCkYaYunYuanRenWuState("" +
				 * app.cardId, "" + app.userZhanghao)) {
				 * getActivity().runOnUiThread(new Runnable() {
				 *
				 * @Override public void run() { dialog.dismiss();
				 * Toast.makeText(getActivity(), "该押运员还有未完成任务..",
				 * Toast.LENGTH_LONG).show(); } }); } else {
				 * getActivity().runOnUiThread(new Runnable() {
				 *
				 * @Override public void run() { dialog.dismiss(); //
				 * 这里暂时先用账号密码登录 useDialog.show(); useDialog.setTitle("押运员验证");
				 * // checkFinger(); } }); } } catch (Exception e) { // TODO
				 * Auto-generated catch block e.printStackTrace(); } }
				 * }).start();
				 */

            }
        });
        quxiao();
    }

    /**
     * 加载我的任务数据
     */
    public void loadRenWu() {
        renwulist.clear();
        dialog.show();
        dialog.setMessage("获取我的任务中...");
        // final TextView tv=(TextView)
        // getActivity().findViewById(R.id.zhuangxiangNum);//

        new Thread(new Runnable() {
            public void run() {
                try {
                    if (cid == null || "".equals(cid)) {
                        cid = edit.getText().toString().trim();
                        app.cardId = cid;
                    }


                    //网络请求由车牌号获取任务列表
                    Log.e("myrewufragment", cid + "cid");
                    str = UpServer.getRenwuList(cid, state, app.userZhanghao);

//                    if (!"".equals(str) && null != str) {
//                        handler.sendEmptyMessage(0);// 成功
//                    } else {
//                        handler.sendEmptyMessage(1);// 没有任务
//                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);// 超时链接
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(1);// 没有任务
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(3);// 其他异常
                }
                if (app.cardId != null && !"".equals(app.cardId)) {
                    try {
                        final String str1 = UpServer.getRenwuList(app.cardId,
                                RwwcFragment.state, app.userZhanghao);
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                if (!"".equals(str1) && null != str1) {
                                    // 成功
                                    zhuangxiangNum.setText("" + Table.doParse(str1).length);
                                } else {
                                    // 没有任务
                                    zhuangxiangNum.setText("0");
                                }
                            }
                        });

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 没有车牌号
                            zhuangxiangNum.setText("0");
                        }
                    });

                }

            }
        }).start();
    }

    /**
     * 获取参数（派工单集合并拼接）---押运员领取任务
     */
    public String getMessageCode() {
        String ss = "";
        for (int i = 0; i < plist.size(); i++) {
            ss += plist.get(i) + "_";
        }
        ss = ss.substring(0, ss.length() - 1);
        return ss;
    }

    /**
     * 押运员领取任务
     */
    public void LingQuRenWu() {

        if (onefingerDialog.isshow()) {
            onefingerDialog.dismiss();
        }

        final String paigongdan = getMessageCode();
        dialog.show();
        dialog.setMessage("获取任务中...");
        new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println("调用参数:" + paigongdan + "==" + userId
                            + "==" + cid);
                    lingqustr = UpServer
                            .setRenwuLingqu(paigongdan, userId, cid);

                    if ("success".equals(lingqustr)) {
                        handler.sendEmptyMessage(6);// 成功
                    } else if ("error".equals(lingqustr)) {
                        handler.sendEmptyMessage(5);// 领取失败
                    } else {
                        handler.sendEmptyMessage(7);

                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(8);// 超时链接

                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(7);// 没有任务

                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(9);// 其他异常

                }
            }
        }).start();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (app.back.equals("back")) {
            back.setText("返回");
        }
        if ("".equals(cid) || cid == null) {
            getCarId();
        } else {
            loadRenWu();
            renwulayout.setVisibility(View.GONE);
            renwu_list_layout.setVisibility(View.VISIBLE);
            renwu_list.setAdapter(adapter);
            queding.setEnabled(true);
            queding.setBackgroundResource(R.drawable.button_blue_selector);
            chepaihao.setText("车牌号:" + cid);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        try {
            listener = (MyRwListener) activity;
        } catch (Exception e) {
        }
        super.onAttach(activity);
    }

    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                   final int position, long arg3) {
        // 弹出Dialog 提示是否要进行删除
        deleteDialog.show();
        deleteDialog.setTitle("是否要删除");
        deleteDialog.setPositiveButton("确定", new OnClickListener() {

            public void onClick(View arg0) {
                renwulist.remove(position);
                listener.tranmsg(renwulist.size() + "");
                adapter.notifyDataSetChanged();
            }
        });
        quxiao();
        return true;// 防止其在触发列表点击事件
    }

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        rw = renwulist.get(arg2);//
        bundle.putSerializable("rw", (Serializable) rw);
        bundle.putString("cid", cid);
        bundle.putSerializable("user", user);
        mCallback.onArticleSelected(StartFwFragment.START_FUWU_TAG, bundle,
                MyRenwuFragment.this);
    }

    public void onClick(View arg0) {// 测试刷新键
        switch (arg0.getId()) {
            case R.id.shuaxin:
                if (flag) {
                    if (cid != null) {
//                        loadRenWu();
                    } else {
//                        getCarId();
                    }
                }

                break;

            case R.id.lin_pc://  盘库方法   fragment 跳转查库的方法
                startActivity(new Intent(MyRenwuFragment.this.getActivity(), PKListInfoActivity.class));
                break;
            case R.id.lincheck:  //  盘库的代码
                startActivity(new Intent(MyRenwuFragment.this.getActivity(), CKListInfoActivity.class));//  名字写反了

                break;
//            case R.id.renwu_shousuo:
//                if (TextUtils.isEmpty(edit.getText().toString())) {
//                    return;
//                }

//                cid = edit.getText().toString().trim();
//                Log.e("myrenwufragment", "从搜索中获取值cid==" + cid);
//                app.cardId = cid;
//                app.cardId = cid;
//保存数据
//                if (edit.getText().toString().trim() != null || edit.getText().toString().trim().equals("") && flagtest == false) {
//
//                    SharedPreferences sp = getActivity().getSharedPreferences("sp_demo", getActivity().MODE_PRIVATE);
//                    SharedPreferences.Editor editor = sp.edit();
//                    editor.putString("1", cid).commit();
//                    flagtest = true;
//                    Log.e("myrenwufragment", "");
//                }
//                sp1 = getActivity().getSharedPreferences("sp_demo", getActivity().MODE_PRIVATE);
//                mrfname = sp1.getString("1", "");
//                Log.e("myfragmetn", "mrfname====" + mrfname);
//                loadRenWu();

//                break;
//            case R.id.queding:// 弹出dialog 验证指纹 领取任务
//            /* 提示用户是否领取任务 */
//                if (times == 0) {
//                    openGetMissionDialog();
//
//                } else {
//                    if (threeTimes) {
//                        useDialog.show();
//                        useDialog.setTitle("押运员验证");
//                        return;
//                    }
//                    onefingerDialog.show();
//                    if (mFingerUtil.getThread() == null) {
//                        mFingerUtil.startFinger();
//                    } else {
//                        mFingerUtil.startControl();
//                    }
//                }
//
//                break;
            case R.id.back:
                // Skip.skip(getActivity(), LoginActivity.class, null, 0);
                if (getActivity() != null) {
                    getActivity().onBackPressed();
                }

                break;
        }
    }

    /**
     * @throws
     * @author 名字
     * @Description: 提示用户任务完成状态是否可继续领取任务
     */
    private void noticeBindCar() {
        dialog.show();
        dialog.setMessage("");
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    String result = UpServer.upCkCarRenBangDing(app.cardId,
                            app.userZhanghao);
                    if (!TextUtils.isEmpty(result)) {
                        if ("success".equals(result)) {
                            handler.sendEmptyMessage(18);
                        } else if ("error".equals(result)) {
                            handler.sendEmptyMessage(19);
                        }
                    }
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            dialog.dismiss();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取车牌号
     */

    public void getCarId() {

//        dialog.show();
//        dialog.setMessage("获取车牌号...");
//        new Thread(new Runnable() {
//            public void run() {
//                try {
//
//                    Log.e("myrenwufragmetn", "mrfname====" + mrfname);
//                    cidtest = UpServer.getReturnChePaiHao(app.userZhanghao);//返回所有的车牌号字符串
//
//
//                    Log.e("myrewufragment", "" + UpServer.getReturnChePaiHaoItem(app.userZhanghao));
//                    if (cidtest != null || !"".equals(cidtest)) {
//                        carInfoArr = cidtest.split(";");//得到的数组
//                        if (mrfname == null || mrfname.equals("")) {
//
//                            Log.e("myrewifragmetn", "mrfname===========" + mrfname);
//                        } else {
//
//                            cid = mrfname;
//
//                        }
//
//
//                        Log.e("myrewnfragment", "stt=" + str);
//
//                        cid = UpServer.getReturnChePaiHaoItem(app.userZhanghao);//返回一个车牌号的相关任务列表
//                        app.cardId = cid;
//                        Log.e("myrewnfragment", "cid=" + cid);
//                        handler.sendEmptyMessage(16);// 成功
//                    } else {
//                        handler.sendEmptyMessage(17);// 成功
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    handler.sendEmptyMessage(15);// 失败
//                }
//            }
//        }).start();
    }

    /**
     * 获取车牌号重试
     */
    public void OnClickGetCarId() {
        deleteDialog.show();
        deleteDialog.setTitle("车牌号获取失败");
        deleteDialog.setPositiveButton("确定", new OnClickListener() {
            public void onClick(View arg0) {
                getCarId();
            }
        });
        quxiao();
    }

    /**
     * 加载失败是重试方法
     */
    public void OnClick() {
        deleteDialog.show();
        deleteDialog.setPositiveButton("确定", new OnClickListener() {
            public void onClick(View arg0) {
                loadRenWu();
            }
        });
        quxiao();
    }

    /**
     * 领取任务失败重试
     */
    public void OnClickLingqu() {
        deleteDialog.show();
        deleteDialog.setPositiveButton("确定", new OnClickListener() {
            public void onClick(View arg0) {
                LingQuRenWu();
            }
        });
        quxiao();
    }

    /**
     * 用户登录失败重试
     */
    public void OnLoginClick() {
        useDialog.show();
        useDialog.setTitle("押运员验证");
        /*
         * deleteDialog.show(); deleteDialog.setTitle("重新登录");
		 * deleteDialog.setPositiveButton("确定", new OnClickListener() { public
		 * void onClick(View arg0) {
		 * 
		 * } }); quxiao();
		 */
    }

    /**
     * 确定点击事件 取消
     */
    public void quxiao() {
        deleteDialog.setNegativeButton("取消", new OnClickListener() {
            public void onClick(View arg0) {
            }
        });
    }

    /**
     * 验证指纹
     */
    public void checkFinger() {
        if (plist.size() > 0) {
            onefingerDialog.show();
            onefingerDialog.setName("小王");
            // 模仿验证指纹
            new Thread(new Runnable() {
                public void run() {
                    try {
                        // UpServer.yanzhengfinger(corpId, roleId, cValue);
                        handler.sendEmptyMessage(5);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            Toast.makeText(getActivity(), "请输入车牌号", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 用户验证
     */
    public void yanzhengUser(final String name, final String pwd) {
        dialog.show();
        dialog.setMessage("正在验证用户...");

        if (!userId.equals(app.userZhanghao)) {
            Toast.makeText(getActivity(), "必须与登录账号一致..", Toast.LENGTH_LONG)
                    .show();
            dialog.dismiss();
            return;
        }
        new Thread(new Runnable() {
            public void run() {
                try {
                    user = UpServer.login(name, pwd);
                    if (user != null) {
                        handler.sendEmptyMessage(11);
                    } else {
                        handler.sendEmptyMessage(12);// 查无此人信息
                    }
                } catch (SocketTimeoutException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(13);// 超时链接
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(12);// 查无此人信息
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(14);// 登录异常
                }
            }
        }).start();
    }

    /**
     * 显示View
     */
    public void showView() {
        chepaihao.setText("车牌号:" + cid);
        renwulayout.setVisibility(View.GONE);
        renwu_list_layout.setVisibility(View.VISIBLE);
        if ("车牌号不存在".equals(str)) {
            queding.setEnabled(false);
            queding.setBackgroundResource(R.drawable.button_gray_selector);
            renwu_list_layout.setVisibility(View.GONE);
            renwulayout.setVisibility(View.VISIBLE);
            youqingtishi.setText("车牌号不存在");
            listener.tranmsg(0 + "");
            app.size = renwulist.size();
        } else {
            tables = Table.doParse(str);
            renwulist.clear();
            plist.clear();
            initMessage();
            renwu_list.setAdapter(adapter);
            adapter.updateList(renwulist);
            listener.tranmsg(renwulist.size() + "");
            app.size = renwulist.size();
            listener.trancid(cid);
            // 判断领取任务的状态 未领取才可以点击
            if ("0".equals(tables[0].get("paigongdanstate").get(0))) {
                queding.setEnabled(true);
                queding.setBackgroundResource(R.drawable.button_blue_selector);
            } else {
                queding.setEnabled(false);
                queding.setBackgroundResource(R.drawable.button_gray_selector);
            }
        }
    }

    /**
     * dialog no dismiss
     */
    OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }
    };

    /**
     * 解析数据
     */
    public void initMessage() {
        for (int j = 0; j < tables.length; j++) {
            plist.add(tables[j].get("paigongdan").get(0));// 派工单
            RenWuClass rw = new RenWuClass();
            rw.setPaigongDan(tables[j].get("paigongdan").get(0));
            rw.setStartTime(tables[j].get("kaishiShijian").get(0));
            rw.setDate(tables[j].get("fuwuRiqi").get(0));
            rw.setCompany(tables[j].get("qiyemingcheng").get(0));
            rw.setAddress(tables[j].get("fuwuDidian").get(0));
            rw.setEndTime(tables[j].get("jiesuShijian").get(0));
            rw.setLine(tables[j].get("fuwuXianlu").get(0));
            rw.setType(tables[j].get("fuwumoshi").get(0));
            rw.setService(tables[j].get("fuwuleibie").get(0));
            rw.setState(tables[j].get("paigongdanstate").get(0));

            Log.e("", "mrfname==============" + mrfname);

            renwulist.add(rw);
            listener.tranmsg(renwulist.size() + "");
        }
    }

    /**
     * 初始化提示框
     */
    public void getDiaog() {
        dmanager = new DialogManager(getActivity());
        useDialog = dmanager.getUserLoginDialog();
        dialog = dmanager.getLoginDialog();
        deleteDialog = dmanager.getDeleteDialog();
        if (onefingerDialog == null) {
            onefingerDialog = new OneFingerDialog(getActivity()).builder();
        }
    }

    @Override
    public void onStop() {
        flag = false;
        super.onStop();
//        if (mFingerUtil != null) {
//            mFingerUtil.stopFinger();
//        }
    }

    @Override
    public void getFingerValue(byte[] value) {
//        mFingerUtil.stopControl();
        String corpId = null;
        String roleId = null;
        corpId = App.getApp().user.getOrganizationId();
        System.out.println("corpId=========" + corpId);
        roleId = Constant.YyRoleId;
//        mFingerUtil.startTconfrim(corpId, roleId, value);

    }

    @Override
    public void getFingerBitmap(Bitmap bitmap) {
        if (!onefingerDialog.isshow()) {
            onefingerDialog.show();
        }
        onefingerDialog.setImageBitmap(bitmap);
    }

    @Override
    public void getFingerSuccess(User user) {
        times = 0;
        if (!user.getAccount().equals(app.userZhanghao)) {
            Toast.makeText(getActivity(), "必须与登录账号一致..", Toast.LENGTH_LONG).show();
            getFingerFail();
            return;
        }
        this.user = user;
        this.user.setUserId(Constant.YyRoleId);
        this.user.setOrganizationId(App.getApp().user.getOrganizationId());
        if (!onefingerDialog.isshow()) {
            onefingerDialog.dismiss();
        }

//        mFingerUtil.stopControl();
        userId = user.getAccount();
        LingQuRenWu();
    }

    /**
     * 指纹的三次验证
     */
    @Override
    public void getFingerFail() {
        if (times == 3) {
            threeTimes = true;
        } else {
            times++;
            threeTimes = false;
            if (times == 3) {
                threeTimes = true;
            }
        }

        deleteDialog
                .setTitle(
                        times == 3 ? "指纹验证失败3次,请使用密码登陆" : "指纹验证失败" + times
                                + "次")
                .setOnlyButton()
                .setkeyListener(keylistener)
                .setPositiveButton(times == 3 ? "密码登陆" : "重新验证",
                        new OnClickListener() {

                            @Override
                            public void onClick(View arg0) {

								/* 判断错误次数，3次打开密码登陆界面 */
                                if (threeTimes) {
                                    if (onefingerDialog != null) {
                                        onefingerDialog.dismiss();
                                    }
                                    useDialog.show();
                                    return;
                                }
                                /* 开启指纹数据发送开关 */
//                                mFingerUtil.startControl();
                            }
                        }).show();
    }


}
